package com.smart.translator.device;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.util.Log;

public class BleDeviceManager {
    private static BleDeviceManager instance;
    private BluetoothGatt bluetoothGatt;
    private BluetoothGattCharacteristic writeCharacteristic;

    private BleDeviceManager() {}

    public static BleDeviceManager getInstance() {
        if (instance == null) {
            instance = new BleDeviceManager();
        }
        return instance;
    }

    public void setBluetoothGatt(BluetoothGatt gatt) {
        Log.d("BLE", "setBluetoothGatt: " + gatt);
        this.bluetoothGatt = gatt;
    }

    public void setWriteCharacteristic(BluetoothGattCharacteristic characteristic) {
        Log.d("BLE", "setWriteCharacteristic: " + characteristic);
        this.writeCharacteristic = characteristic;
    }

    public boolean writeData(byte[] data) {
        Log.d("BLE", "准备写入数据，gatt=" + bluetoothGatt + ", char=" + writeCharacteristic);
        if (bluetoothGatt != null && writeCharacteristic != null) {
            writeCharacteristic.setValue(data);
            boolean result = bluetoothGatt.writeCharacteristic(writeCharacteristic);
            Log.d("BLE", "全局写入数据: " + bytesToHex(data) + ", 结果: " + result);
            return result;
        } else {
            Log.w("BLE", "全局BLE未连接或未找到可写特征");
            return false;
        }
    }

    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString();
    }
} 